//
//  CommitViewModel.swift
//  Git@OSC
//
//  Created by AeternChan on 10/13/15.
//  Copyright © 2015 oschina. All rights reserved.
//

import UIKit
import Alamofire
import ReactiveCocoa
import SwiftyJSON

enum DiffType {
    case All
    case Added
    case Renamed
    case Removed
    case Modified
}

class CommitViewModel: NSObject {

    var namespace: String!
    var commit: Commit!
    
    var allFiles = [Diff]()
    var diffTypes = MutableProperty<[DiffType]>([])
    var addedFiles = [Diff]()
    var renamedFiles = [Diff]()
    var removedFiles = [Diff]()
    var modifiedFiles = [Diff]()
    
    var page = MutableProperty<Int>(0)
    var notes = [Note]()
    
    func fetchDiff() {
        Alamofire.request(.GET, API.projects + namespace + API.commits + "\(commit.id)" + API.diff)
            .responseJSON { response in
                
                if response.result.isSuccess {
                    let json = JSON(response.result.value!)
                    
                    for (_, diffJSON) in json {
                        let diff = Diff(diffJSON)
                        self.allFiles.append(diff)
                        
                        if diff.isAdded {self.addedFiles.append(diff)}
                        if diff.isRenamed {self.renamedFiles.append(diff)}
                        if diff.isRemoved {self.removedFiles.append(diff)}
                        if !diff.isAdded && !diff.isRenamed && !diff.isRemoved {
                            self.modifiedFiles.append(diff)
                        }
                    }
                    
                    if self.addedFiles.count > 0 {self.diffTypes.value.append(.Added)}
                    if self.removedFiles.count > 0 {self.diffTypes.value.append(.Removed)}
                    if self.renamedFiles.count > 0 {self.diffTypes.value.append(.Renamed)}
                    if self.modifiedFiles.count > 0 {self.diffTypes.value.append(.Modified)}
                    if self.diffTypes.value.count > 1 {self.diffTypes.value.insert(.All, atIndex: 0)}
                } else {
                    
                }
        }
    }
    
    func fetchNotes() {
        Alamofire.request(.GET, API.projects + namespace + API.commits + "\(commit.id)" + API.notes)
            .responseJSON { response in
                
                if response.result.isSuccess {
                    let json = JSON(response.result.value!)
                    
                    for (_, noteJSON) in json {
                        let note = Note(noteJSON)
                        self.notes.append(note)
                    }
                    
                    self.page.value += 1
                } else {
                    
                }
        }
    }
}
